<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue';
import { getAllPermission } from '@/service/api/system';
defineOptions({
  name: 'RouteModal'
});
const showModal = ref(false);
const loading = ref(false);

const allItems = ref<Api.System.Permission[]>([]);
const items = ref<Api.System.Permission[]>([]);
const noMore = computed(() => items.value.length >= allItems.value.length);
const batchSize = 5; // 每次加载的数量
const currentIndex = ref(0); // 当前加载到的索引
const cities = ref<number[]>([]);

const handleLoad = async () => {
  // 如果正在加载、没有更多数据或源数据为空，则不执行加载
  if (loading.value || noMore.value || allItems.value.length === 0) return;
  loading.value = true;

  try {
    // 模拟网络请求延迟
    await new Promise<void>(resolve => {
      setTimeout(resolve, 500);
    });

    // 计算本次要加载的数据范围
    const endIndex = Math.min(currentIndex.value + batchSize, allItems.value.length);
    // 从allItems中截取部分数据
    const newItems = allItems.value.slice(currentIndex.value, endIndex);

    // 添加到现有列表中
    items.value.push(...newItems);
    // 更新当前索引
    currentIndex.value = endIndex;
  } finally {
    loading.value = false;
  }
};

function handleShowModal(params: { permissionIds: number[] }) {
  showModal.value = true;
  nextTick(() => {
    cities.value = params.permissionIds;
  });
}

onMounted(async () => {
  const { data, error } = await getAllPermission();
  if (error) return;
  allItems.value = data;
  items.value = [];
  currentIndex.value = 0;
  handleLoad();
});

defineExpose({
  handleShowModal,
  cities
});
</script>

<template>
  <div>
    <NInfiniteScroll class="infinite-scroll" :distance="10" @load="handleLoad">
      <NCheckboxGroup v-model:value="cities">
        <div v-for="item in items" :key="item.id">
          <NCheckbox :value="item.id" :label="item.name" />
        </div>
      </NCheckboxGroup>
      <div v-if="loading" class="text">加载中...</div>
      <div v-if="noMore" class="text">没有更多了 🤪</div>
    </NInfiniteScroll>
  </div>
</template>

<style scoped>
.infinite-scroll {
  height: 240px;
}
</style>
